from flask import Blueprint,request,jsonify
import json
from database import *
from conf.comm import sqlalchemy_context

bp_cates = Blueprint('cates', __name__)



# 
def xtree(data):
    tree = {}
    list = []
    # 解析程字典
    for i in data:
        tree[i['id']] = i
    for j in data:
        # 判断父id是否等于0  等于0则直接添加到列表里
        if j['parent'] ==0:
            list.append(j)
        else:
            # 如果son不在tree 字典里  则自己定义空字典  如果在 则直接添加
            if 'son' not in tree[j['parent']]:
                tree[j['parent']]['son'] = []
            tree[j['parent']]['son'].append(j)
    return list
@bp_cates.route('/addclass/',methods=['POST','GET'])
@sqlalchemy_context()
# 添加分类接口
def addclass():
    if request.method =='POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        
        try:
            cate = Cate(name=data['name'],level=data['level'],params=data['params'])
            db.session.add(cate)
            db.session.commit()
            return jsonify({'code':200,'mes':'添加成功'})
        except:
            return jsonify({'code':10031,'mes':'添加失败'})
    elif request.method == 'GET':
        cate = Cate.query.all()
        list = []
        for i in cate:
            list.append({'id':i.id,'name':i.name,'level':i.level,'parent':i.parent,'params':i.params})
        list = xtree(list)
        return jsonify({'code':200,'list':list})

